#include "Settings.h"

void Settings::load(const QString& filename)
{
	QFile file(filename);
	if(!file.open(QFile::ReadOnly))
		return;

	QXmlInputSource source(&file);
	
	QXmlSimpleReader reader;
	reader.setContentHandler(this);
	reader.setErrorHandler(this);

	m_settingsStarted = false;

	reader.parse(&source);

	// See if the settings haven't been setup yet
	if(m_settings.value("IsSetup") == "no")
	{
		this->addDefaultSettings();
		m_settings["IsSetup"] = "yes";
		save();
	}
}

void Settings::save(const QString& filename)
{
	QFile file(filename);
	if(!file.open(QFile::WriteOnly))
		return;

	QXmlStreamWriter writer(&file);
	writer.setAutoFormatting(true);

	writer.writeStartDocument();

	writer.writeStartElement("Settings");

	QMapIterator<QString, QString> it(m_settings);

	while(it.hasNext())
	{
		it.next();

		writer.writeStartElement(it.key());
		writer.writeAttribute("value", it.value());
		writer.writeEndElement();
	}

	writer.writeEndElement();

	writer.writeEndDocument();
}

void Settings::setValue(const QString& key, const QString& value)
{
	m_settings.insert(key, value);
}

QString Settings::getValue(const QString& key)
{
	return m_settings.value(key);
}

void Settings::addDefaultSettings()
{
	// Get the save directory
	QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", QSettings::NativeFormat);
	QString dir = settings.value("My Pictures").toString();

	dir += "/CamWhore/";

	setValue("SaveDirectory", dir);
}

bool Settings::fatalError(const QXmlParseException& exception)
{
	qDebug() << "Fatal XML error: (" << exception.lineNumber() << ":" << exception.columnNumber() << ") - " << exception.message() << ".\n";
	return false;
}

bool Settings::startElement(const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts)
{
	if(qName == "Settings")
	{
		m_settingsStarted = true;
		return true;
	}

	if(!m_settingsStarted)
		return true;

	m_settings[qName] = atts.value("value");
	qDebug() << qName << " = " << atts.value("value") << ".\n";

	return true;
}
